package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.widget.ItemView;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.vo.TwoBeanVo;
import com.umeng.analytics.MobclickAgent;

/**
 * @{# CreateZhiliaofanganActivity.java Create on 2014年10月24日 下午9:32:30
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0
 * @description
 * 
 *              模板创建或修改
 */

@SuppressLint("InflateParams")
public class CreateZhiliaofanganActivity extends BasicActivity {

	private EditText mEditTemplateName;

	private EditText mEditPatientZhengzhunagGaishu;

	private ItemView mItemviewQuestionCategory;

	private EditText mEditBingzhengtuiduan;

	private EditText mEditYongyao;

	private EditText mEditYizhu;

	private LinearLayout mLlCuoshi;

	private ArrayList<View> cuoshiView;

	private String templateId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_zhiliao_fangan);

		mEditTemplateName = (EditText) findViewById(R.id.edit_template_name);
		mEditPatientZhengzhunagGaishu = (EditText) findViewById(R.id.edit_patient_zhengzhunag_gaishu);
		mItemviewQuestionCategory = (ItemView) findViewById(R.id.itemview_question_category);
		mEditBingzhengtuiduan = (EditText) findViewById(R.id.edit_bingzhengtuiduan);
		mEditYongyao = (EditText) findViewById(R.id.edit_yongyao);
		mEditYizhu = (EditText) findViewById(R.id.edit_yizhu);
		mLlCuoshi = (LinearLayout) findViewById(R.id.ll_cuoshi);

		templateId = getIntent().getStringExtra(Constant.IDENTITY_KEY_ID);

		init();
		if (!CommonUtility.isNull(templateId)) {
			setNavTitle("修改解答模板");
		} else {
			setNavTitle("创建解答模板");
		}
		setNavRightBtn("提交");

		String[] datas = getIntent().getStringArrayExtra(Constant.IDENTITY_KEY);
		TwoBeanVo vo = (TwoBeanVo) getIntent().getSerializableExtra(
				Constant.IDENTITY_KEY_1);
		String templateName = getIntent().getStringExtra(
				Constant.IDENTITY_KEY_TITLE);
		mEditTemplateName.setText(templateName);

		if (!CommonUtility.isNull(datas)) {
			mEditPatientZhengzhunagGaishu.setText(datas[0]);
			mItemviewQuestionCategory.setTextValueValue(datas[3]);
			mEditBingzhengtuiduan.setText(datas[4]);
			mEditYongyao.setText(datas[1]);
			mEditYizhu.setText(datas[2]);
		}

		if (!CommonUtility.isNull(vo)) {
			String[][] cuoshiDatas = vo.datas;
			if (!CommonUtility.isNull(cuoshiDatas)) {
				int length = cuoshiDatas.length;
				if (length > 0) {
					for (int i = 0; i < length; i++) {
						String[] cuoshiData = cuoshiDatas[i];
						if (CommonUtility.isNull(cuoshiView)) {
							cuoshiView = new ArrayList<View>();
						}
						View v = LayoutInflater.from(activity).inflate(
								R.layout.item_cuoshi, null);
						int count = mLlCuoshi.getChildCount();
						mLlCuoshi.addView(v, count);
						TextView text_cuoshi_num = (TextView) v
								.findViewById(R.id.text_cuoshi_num);
						count++;
						text_cuoshi_num.setText("措施" + count);
						EditText edit_yongyao = (EditText) v
								.findViewById(R.id.edit_yongyao);
						EditText edit_yizhu = (EditText) v
								.findViewById(R.id.edit_yizhu);
						Button btnDel = (Button) v
								.findViewById(R.id.btn_delete);
						btnDel.setTag(v);
						edit_yongyao.setText(cuoshiData[0]);
						edit_yizhu.setText(cuoshiData[1]);
						cuoshiView.add(v);
					}
				}
			}
		}
		mEditPatientZhengzhunagGaishu
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						EditText textView = (EditText) v;
						String hint;
						if (hasFocus) {
							hint = textView.getHint().toString();
							textView.setTag(hint);
							textView.setHint(null);
						} else {
							hint = textView.getTag().toString();
							textView.setHint(hint);
						}
					}
				});

		CommonUtility.showKeyboard(mEditTemplateName);
	}

	public void onClick(final View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.ll_add_cuoshi) {
			if (CommonUtility.isNull(cuoshiView)) {
				cuoshiView = new ArrayList<View>();
			}
			View v = getLayoutInflater().inflate(R.layout.item_cuoshi, null);
			int count = mLlCuoshi.getChildCount();
			mLlCuoshi.addView(v, count);
			TextView text_cuoshi_num = (TextView) v
					.findViewById(R.id.text_cuoshi_num);
			count++;
			text_cuoshi_num.setText("措施" + count);
			Button btnDel = (Button) v.findViewById(R.id.btn_delete);
			btnDel.setTag(v);
			cuoshiView.add(v);
		} else if (id == R.id.itemview_question_category) {
			startActivityForResult(new Intent(activity,
					ZhengzhuangActivity.class), 0);
		} else if (id == R.id.text_right) {
			try {
				String tempName = CommonUtility.getText(mEditTemplateName);
				if (CommonUtility.isNull(tempName)) {
					CommonUtility.tip(activity, "请输入模板标题");
					return;
				}
				String bingzheng_gaishu = CommonUtility
						.getText(mEditPatientZhengzhunagGaishu);
				if (CommonUtility.isNull(bingzheng_gaishu)) {
					CommonUtility.tip(activity, "请输入解答意见");
					return;
				}
				String yongyao = CommonUtility.getText(mEditYongyao);
				String yizhu = CommonUtility.getText(mEditYizhu);
				// if (CommonUtility.isNull(yizhu)) {
				// CommonUtility.tip(activity, "请输入医嘱");
				// return;
				// }

				String questionCategory = mItemviewQuestionCategory
						.getTextValueValue();
				// if (CommonUtility.isNull(questionCategory)) {
				// CommonUtility.tip(activity, "请选择问题分类");
				// return;
				// }

				String bingZhengTuiDuan = CommonUtility
						.getText(mEditBingzhengtuiduan);
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put("Malady", bingzheng_gaishu);
				params.put("Disease_Inference", bingZhengTuiDuan);
				params.put("Symptom", questionCategory);
				params.put("Drug_0", yongyao);
				params.put("Advice_0", yizhu);
				params.put("Title", tempName);
				if (!CommonUtility.isNull(templateId)) {
					params.put("taid", templateId);
				}
				params.put(Constant.PARAM_API, "Temple.Answer.Set");
				params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
				if (!CommonUtility.isNull(cuoshiView)) {
					int cuoshiSize = cuoshiView.size();
					params.put("TreatMentsCount", cuoshiSize + 1);
					for (int i = 0; i < cuoshiSize; i++) {
						View cuoshi = cuoshiView.get(i);
						EditText edit_yongyao = (EditText) cuoshi
								.findViewById(R.id.edit_yongyao);
						EditText edit_yizhu = (EditText) cuoshi
								.findViewById(R.id.edit_yizhu);
						params.put("Drug_" + (i + 1),
								CommonUtility.getText(edit_yongyao));
						params.put("Advice_" + (i + 1),
								CommonUtility.getText(edit_yizhu));
					}
				} else {
					params.put("TreatMentsCount", 1);
				}
				RequestTaskIntercept.requestIntercept(activity,
						Constant.URL.REQUEST, new RequestHandler(activity,
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											JSONObject object = (JSONObject) o;
											if (CommonUtility
													.response200(object)) {
												CommonUtility.toast(activity,
														"模板创建成功");
												Intent intent = new Intent(
														Constant.RECEIVER_CREATE_TEMPLATE);
												LocalBroadcastManager
														.getInstance(activity)
														.sendBroadcast(intent);
												finish();
											} else {
												try {
													CommonUtility.toast(
															activity,
															object.getString(Constant.JSON_PARAM_RESULTMESSAGE));
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
										}
									}
								}), params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (id == R.id.btn_delete) {
			OAlert alert = new OAlert(activity);
			alert.setOK("确认");
			alert.setCancel("取消");
			alert.setTitle("确认删除这个措施吗？");
			alert.show();
			alert.setListener(new OAlertListener() {

				@Override
				public boolean onOK(OAlert alert) {
					View child = (View) view.getTag();
					mLlCuoshi.removeView(child);
					cuoshiView.remove(child);
					return false;
				}

				@Override
				public boolean onCancel(OAlert alert) {
					return false;
				}
			});
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (!CommonUtility.isNull(data)) {
			String value = data.getStringExtra(Constant.IDENTITY_KEY);
			switch (resultCode) {
			case Constant.ACTIVITY_CHOOSE_ZHENGZHUANG:
				mItemviewQuestionCategory.setTextValueValue(value);
				break;
			}
		}
	}
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
}
